<?php

namespace App\Http\Middleware;

use App\Models\Manager\UserPermissionsRelation;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //如果id为1则用户为root用户，拥有所有权限
        $userId = auth()->user()->id;
        $user = User::find($userId);


        //检查用户权限
        if ($userId === 1){
            return $next($request);
        }
        $permissions = User::all()->find(auth()->user()->id)->Permission()->get();
        foreach ($permissions as $item){
            if ($request->route()->named($item->permissionName)){
                return $next($request);
            }
        }

        //检查组权限
        $groups = $user->Group()->get();
        foreach ($groups as $group){
            if ($group['id']===1){
                return $next($request);
            }
            $groupPermissions = $group->Permission()->get();
            foreach ($groupPermissions as $permission){
                if ($request->route()->named($permission->permissionName)){
                    return $next($request);
                }
            }
        }

        return response()->json([
           "code" => 401,
           "msg"   => "当前用户没有操作权限"
        ],401);
    }
}
